#include"Socket.hpp"
#include"InetAddr.hpp"
#include"Protocol.hpp"
#include<iostream>
#include<string>
#include<cstdint>

void Usage(std::string proc)
{
    std::cout << "Usage " << "serverip serverport"<<std::endl;
}

//./client serverip serverport
int main(int argc , char* argv[])
{   
    if(argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //创建套接字
    std::unique_ptr<TcpSocket> sockptr = std::make_unique<TcpSocket>();
    sockptr->BuildClientSocketMethod();
    //向服务器发起连接
    InetAddr server(serverport , serverip);
    if(sockptr->Connect(server))
    {
        std::string inbuffer;//读取的数据放在此处
        //连接成功
        //获取客户所要发送的数据，构建请求；客户端也是一个死循环
        while(true)
        {
            //1、构建请求
            Request req;
            std::cout << "Please enter x: ";
            std::cin >> req._x;
            std::cout << "Please enter y: ";
            std::cin >> req._y;
            std::cout << "Please enter oper: ";
            std::cin >> req._oper;

            //2、序列化
            std::string jsonstr;
            req.Serialize(&jsonstr);

            //3、打包
            std::string sendstr = Protocol::Package(jsonstr);

            //4、发送
            sockptr->Send(sendstr);

            //5、读取
            sockptr->Recv(&inbuffer);

            //6、解包
            std::string package;
            int n = Protocol::Unpack(inbuffer , &package);
            if(n > 0)
            {
                Responce resp;
                //7、反序列化
                bool r = resp.Deserialize(package);
                if(r)
                {
                    resp.Print();
                }
            }
        }
    }

    return 0;
}